//
//  HotViewController.m
//  project
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "HotViewController.h"
#import "HotListCell.h"
#import "PKRequestManager.h"
#import "ListModel.h"
#import "HotDetailViewController.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
#import "SearchViewController.h"


@interface HotViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)UICollectionView *collection;
@property (nonatomic, strong)NSMutableArray *dataSourceArray;
@property (nonatomic, strong)FMDatabase *dataBase;

@end


@implementation HotViewController

static int limit = 0;
-(void)requsteData
{
    limit = 0;
    [PKRequestManager requestWithTypeP:GET urlString:@"https://api.liwushuo.com/v2/items?gender=2&generation=2&limit=50&offset=0" parDic:nil finish:^(NSData *data) {
        
        [_dataBase executeUpdate:@"delete from HotList"];
        [_dataBase executeUpdate:@"insert into HotList values (?)", data];
        [self.dataSourceArray removeAllObjects];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic in array)
        {
            NSDictionary *modelDic = dic[@"data"];
            ListModel *model = [[ListModel alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
        }
        [self.collection reloadData];
        [self.collection.header endRefreshing];
        
    } error:^(NSError *error) {
        
        NSLog(@"%@", error);
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(kWidth / 2 - 20, 30, 40, 20);
    label.text = @"热门";
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    self.navigationItem.title = @"热门";
    self.view.backgroundColor = [UIColor whiteColor];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"sousuo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(search:)];
    
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    CGFloat item = (kWidth - 30)/2;
    layout.itemSize = CGSizeMake(item, item + 80);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 50) collectionViewLayout:layout];
    _collection.dataSource = self;
    _collection.delegate = self;
     _collection.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    
    [_collection registerClass:[HotListCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collection];
    _dataSourceArray = [NSMutableArray array];
    
    limit = 0;
    // 下拉刷新
    __weak HotViewController *newSelf = self;
   // self.collection.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
  //      [newSelf requsteData];
  //  }];
    
      MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(requsteData)];
    NSArray *arr = @[[UIImage imageNamed:@"1.tiff"],[UIImage imageNamed:@"2.tiff"],[UIImage imageNamed:@"3.tiff"],[UIImage imageNamed:@"4.tiff"]];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.collection.header = header;

    
    // 上拉加载
    self.collection.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [newSelf requestMoreData];
    }];
    
    // 数据持久化
    // 获得数据库路径
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"project.db"];
    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open])
    {
        [_dataBase executeUpdate:@"create table HotList (data blob)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from HotList"];
    while ([resultSet next])
    {
        NSData *data = [resultSet dataForColumn:@"data"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic in array)
        {
            NSDictionary *modelDic = dic[@"data"];
            ListModel *model = [[ListModel alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
        }
    }

    if (_dataSourceArray.count != 0)
    {
        [self.collection reloadData];
    }
    
     [self requsteData];
}

-(void)search:(UIBarButtonItem *)search
{
    SearchViewController *searchVC = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.dataSourceArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
   ListModel *model = self.dataSourceArray[indexPath.row];
    [cell ConfigModel:model];

    return cell;
                         
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ListModel *model = self.dataSourceArray[indexPath.row];
    HotDetailViewController *hotDetailVC = [[HotDetailViewController alloc]init];
    hotDetailVC.model = model;
    [self.navigationController pushViewController:hotDetailVC animated:YES];
    
}

-(void)requestMoreData
{
    limit = limit + 50;
    NSString *urlString = [NSString stringWithFormat:@"https://api.liwushuo.com/v2/items?gender=2&generation=2&limit=50&offset=%d", limit];
    [PKRequestManager requestWithTypeP:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        
        NSLog(@"%@",data);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSDictionary *dic = dict[@"data"];
        NSArray *array = dic[@"items"];
        for (NSDictionary *dic in array)
        {
            NSDictionary *modelDic = dic[@"data"];
            ListModel *model = [[ListModel alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataSourceArray addObject:model];
        }
        [self.collection reloadData];
        [self.collection.footer endRefreshing];
        
    } error:^(NSError *error) {
        
        NSLog(@"%@", error);
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
